package com.douma.task;

import com.alibaba.fastjson.JSON;
import com.douma.dao.ShopDao;
import com.douma.dto.Shop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 抖码课堂，专注中国程序员基础内功修炼
 * 官网：douma-tech.com
 * 公众号：抖码课堂
 *
 * @作者 : 老汤
 */

// @Component
public class SyncShops2RedisTask implements ApplicationRunner {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ShopDao shopDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("【启动】同步商铺数据的定时任务");

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                logger.info("【开始执行】同步商铺数据任务");
                // 1. 从 MySQL 中拿到所有商铺数据
                // 适用于数据量比较少的场景
                List<Shop> shops = shopDao.queryAll();
                // 2. 写到 Redis 缓存
                shops.forEach(shop -> {
                    stringRedisTemplate.opsForValue()
                            .set("shop:" + shop.getId(), JSON.toJSONString(shop));
                });
                logger.info("【结束】同步商铺数据任务");
            }
        };

        // 最多需要忍受 60 秒的数据不一致
        new Timer().scheduleAtFixedRate(task, 1000, 60 * 1000);
    }
}
